package stack;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * 使用栈实现计算器(后缀逆波兰表达式）
 */
public class PolandNotation {
    public static void main(String[] args) {
        //逆波兰输入，以空格隔开，求解
        String suffixExpression = "3 4 + 5 * 6 -";
        //传入ArrayList中
        List<String> list = getListStringBySplit(suffixExpression);
        int result = calculate(list);
        System.out.println("[" + suffixExpression + "]=" + result);

        //中缀输入，逆波兰求解
        String midSuffixExpression = "((2+3)*4)";
        List<String> stringList = getListByMid(midSuffixExpression);
        List<String> expressionList = toInfixExpressionList(stringList);
        System.out.println(expressionList);
        int calculate = calculate(expressionList);
        System.out.println(calculate);
    }

    /**
     * String空格分割存入ArrayList中
     *
     * @param suffixExpression
     * @return
     */
    public static List<String> getListStringBySplit(String suffixExpression) {
        String[] split = suffixExpression.split(" ");
        List<String> list = new ArrayList<>();
        for (String str : split) {
            list.add(str);
        }
        return list;
    }

    /**
     * 逆波兰表达式计算器
     *
     * @param list
     * @return
     */
    public static int calculate(List<String> list) {
        Stack<String> stack = new Stack<String>();
        for (String item : list) {
            if (item.matches("\\d+")) {
                stack.push(item);
            } else {
                int num1 = Integer.parseInt(stack.pop());
                int num2 = Integer.parseInt(stack.pop());
                int res = 0;
                if (item.equals("+")) {
                    res = num2 + num1;
                } else if (item.equals("-")) {
                    res = num2 - num1;
                } else if (item.equals("*")) {
                    res = num2 * num1;
                } else if (item.equals("/")) {
                    res = num2 / num1;
                } else {
                    throw new RuntimeException("运算符有错误");
                }
                stack.push("" + res);
            }
        }
        return Integer.parseInt(stack.pop());
    }

    /**
     * 中缀表达式存入ArrayList
     */
    public static List<String> getListByMid(String midStr) {
        List<String> list = new ArrayList<String>();
        int i = 0;
        String str;
        char c;
        do {
            //若为运算符
            if ((c = midStr.charAt(i)) < 48 || (c = midStr.charAt(i)) > 57) {
                list.add("" + c);
                i++;
            } else {//若为数值
                str = "";
                while (i < midStr.length() && (c = midStr.charAt(i)) >= 48 && (c = midStr.charAt(i)) <= 57) {
                    str += c;
                    i++;
                }
                list.add(str);
            }
        } while (i < midStr.length());
        return list;
    }

    /**
     * 中缀ArrayList转为后缀ArrayList
     */
    public static List<String> toInfixExpressionList(List<String> list) {
        Stack<String> stack = new Stack<String>();
        List<String> result = new ArrayList<String>();
        for (String item : list) {
            if (item.matches("\\d+")) {//若为数值直接进入结果数组
                result.add(item);
            } else if (item.equals("(")) {//若为“(”直接进入栈
                stack.add(item);
            } else if (item.equals(")")) {//若为“)”,依次弹出栈运算符，直至遇到“(”
                while (!stack.peek().equals("(")) {
                    result.add(stack.pop());
                }
                stack.pop();//消除括号
            } else {//运算符
                //当前运算符优先级小于等于栈顶运算符，栈顶运算符转移到结果队列（当前运算符当大哥）
                while (stack.size() != 0 && Operation.getValue(item) <= Operation.getValue(stack.peek())) {
                    result.add(stack.pop());
                }
                stack.push(item);
            }
        }
        while (stack.size() != 0){
            result.add(stack.pop());
        }
        return result;
    }
}

class Operation {
    private static int ADD = 1;
    private static int SUB = 1;
    private static int MUL = 2;
    private static int DIV = 2;

    public static int getValue(String operation) {
        int result = 0;
        switch (operation) {
            case "+":
                result = ADD;
                break;
            case "-":
                result = SUB;
                break;
            case "*":
                result = MUL;
                break;
            case "/":
                result = DIV;
                break;
        }
        return result;
    }
}

